package com.pro.springbootpro.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @author DJR (1210843430@qq.com)
 */
@Component
@Slf4j
public class RedisUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value, 24 * 60 * 60, TimeUnit.SECONDS);
    }

    public void setNoTimeout(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * redis加锁
     *
     * @param key
     * @param value
     * @param expireTime
     * @param timeUnit
     * @return
     */
    public boolean tryLock(String key, String value, int expireTime, TimeUnit timeUnit) {
        Boolean isSuccess = redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, timeUnit);
        if (isSuccess == null || !isSuccess) {
            log.error("申请锁(" + key + "," + value + ")失败");

            return false;
        }
        log.info("申请锁(" + key + "," + value + ")成功");
        return true;
    }

    /**
     * redis释放锁
     *
     * @param key
     * @param value
     */
    public void unLock(String key, String value) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long result = redisTemplate.execute(redisScript, Arrays.asList(key), value);
        if (result == null || result == 0) {
            log.info("释放锁(" + key + "," + value + ")失败,该锁不存在或锁已经过期");
        } else {
            log.info("释放锁(" + key + "," + value + ")成功");
        }
    }


}
